// axios配置  可自行根据项目进行更改，只需更改该文件即可，其他文件可以不动
// The axios configuration can be changed according to the project, just change the file, other files can be left unchanged

import type { AxiosInstance, AxiosResponse } from 'axios';
import { clone } from 'lodash-es';
import type { RequestOptions, Result } from '#/axios';
import type { AxiosTransform, CreateAxiosOptions } from './axios-transform';
import { VAxios } from './axios';
import { checkStatus } from './check-status';
import { ContentTypeEnum } from '@/enums/http-enum';
import { isString, isUndefined, isNull, isEmpty } from 'lodash-es';
import { getToken } from '@/utils/auth';
import { deepMerge } from '@/utils';
import { getDefaultHeaderConfig } from './helper';
import { ElMessage as Message } from 'element-plus';

import { getAppEnvConfig } from '@/utils/env';
import axios from 'axios';

const { VITE_APP_BASE_API } = getAppEnvConfig();

/**
 * @description: 数据处理，方便区分多种处理方式
 */
const transform: AxiosTransform = {
  /**
   * @description: 处理响应数据。如果数据不是预期格式，可直接抛出错误
   */
  transformResponseHook: (res: AxiosResponse<Result>, options: RequestOptions) => {
    const { isTransformResponse } = options;
    // 不进行任何处理，直接返回
    // 用于页面代码可能需要直接获取code，data，message这些信息时开启
    if (!isTransformResponse) {
      return res.data;
    }
    // 错误的时候返回

    const { data } = res;
    if (!data) {
      // return '[HTTP] Request has no return value';
      throw new Error('请求出错，请稍候重试');
    }
    //  这里 code，result，message为 后台统一的字段，需要在 types.ts内修改为项目自己的接口返回格式
    const { errCode: code, data: result, errMessage: message, success, redirect_url } = data;

    // 这里逻辑可以根据项目进行修改
    const hasSuccess = data && success;
    if (hasSuccess) {
      let successMsg = message;

      if (isNull(successMsg) || isUndefined(successMsg) || isEmpty(successMsg)) {
        successMsg = '操作成功';
      }

      if (options.successMessageMode === 'message') {
        Message.success(successMsg);
      }
      return result;
    }

    // 在此处根据自己项目的实际情况对不同的code执行不同的操作
    // 如果不希望中断当前请求，请return数据，否则直接抛出异常即可
    let timeoutMsg = '';
    switch (code) {
      case '20001':
        window.location.href = redirect_url;
        break;
      default:
        if (message) {
          timeoutMsg = message;
        }
    }

    throw new Error(timeoutMsg || '请求出错，请稍候重试');
  },

  // 请求之前处理config
  beforeRequestHook: (origin, options) => {
    const { apiUrl, joinPrefix, urlPrefix } = options;
    const config = {
      ...options,
      ...origin
    }

    if (joinPrefix) {
      config.url = `${urlPrefix}${config.url}`;
    }

    if (apiUrl && isString(apiUrl)) {
      config.url = `${apiUrl}${config.url}`;
    }
    return config;
  },

  /**
   * @description: 请求拦截器处理
   */
  requestInterceptors: (config, options) => {
    // 请求之前处理config
    const token = getToken();
    if (token && (config as Recordable)?.requestOptions?.withToken !== false) {
      // jwt token
      (config as Recordable).headers.Authorization = options.authenticationScheme
        ? `${options.authenticationScheme} ${token}`
        : token;
    }
    return config;
  },

  /**
   * @description: 响应拦截器处理
   */
  responseInterceptors: (res) => {
    const { data: { success, errMessage}, config } = res;
    const { isNeedErrorTip } = config as CreateAxiosOptions;
    if(isNeedErrorTip && !success) {
      Message({
        type: 'error',
        message: errMessage || ''
      })
    }
    return res;
  },

  /**
   * @description: 响应错误处理
   */
  responseInterceptorsCatch: (axiosInstance: AxiosInstance, error: any) => {
    const { response, code, message } = error || {};
    const msg: string = response?.data?.error?.message ?? '';
    const err: string = error?.toString?.() ?? '';
    let errMessage = '';

    if (axios.isCancel(error)) {
      return Promise.reject(error);
    }

    try {
      if (code === 'ECONNABORTED' && message.indexOf('timeout') !== -1) {
        errMessage = '请求超时';
      }
      if (err?.includes('Network Error')) {
        errMessage = '网络异常';
      }

      if (errMessage) {
        Message.error(errMessage);
        return Promise.reject(error);
      }
    } catch (error) {
      throw new Error(error as unknown as string);
    }

    checkStatus(error?.response?.status, msg);
    return Promise.reject(error);
  }
};

function createAxios(opt?: Partial<CreateAxiosOptions>) {
  return new VAxios(
    // 深度合并
    deepMerge(
      {
        timeout: 10 * 1000,
        // 基础接口地址
        // baseURL: globSetting.apiUrl,

        headers: {
          'Content-Type': ContentTypeEnum.JSON,
          ...getDefaultHeaderConfig()
        },
        // 如果是form-data格式
        // headers: { 'Content-Type': ContentTypeEnum.FORM_URLENCODED },
        // 数据处理方式
        transform: clone(transform),
        isShowLoading: true,
        // 是否需要直接提示错误
        isNeedErrorTip: true,
        // 配置项，下面的选项都可以在独立的接口请求中覆盖
        requestOptions: {
          // 默认将prefix 添加到url
          joinPrefix: false,
          // 需要对返回数据进行处理
          isTransformResponse: false,
          // 接口地址
          apiUrl: VITE_APP_BASE_API,
          urlPrefix: ''
        }
      },
      opt || {}
    )
  );
}
export const defHttp = createAxios();
